import ReactDOM from 'react-dom'
import createApp from 'create-app/lib/client'
import routes from '../src'
import config from '../server.config'
import * as $helpers from './helpers'

const __APP_SETTINGS__ = window.__APP_SETTINGS__ || {}

const paths = routes.map(route => route.path)

const viewEngine = {
  render(component, container) {
    logRenderStart()
    const result = ReactDOM.render(component, container)
    setTimeout(logRenderEnd, 0)
    return result
  }
}

const logRenderStart = () => {
  console && console.time && console.time('React#render')
}

const logRenderEnd = () => {
  console && console.timeEnd && console.timeEnd('React#render')
}

const getModule = module => module.default || module

const webpackLoader = loadModule => {
  if ('function' === typeof loadModule) {
    return new Promise(loadModule).then(getModule)
  }
  return getModule(loadModule)
}

const appSettings = {
  type: 'createHistory',
  container: '#root',
  ...__APP_SETTINGS__,
  context: {
    preload: {},
    isClient: true,
    isServer: false,
    ...__APP_SETTINGS__,
    paths,
  },
  routes,
  viewEngine,
  loader: webpackLoader
}

const app = createApp(appSettings)

app.start()